package com.jk1123.dotdog.http;


import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class HttpServletResponseImpl implements HttpServletResponse {
    private OutputStream out;
    /**
     * 响应头
     */
    private Map<String,String> headers=new HashMap<>();
    private byte[] buffer;



    public HttpServletResponseImpl(OutputStream out) {
        this.out = out;
    }

    @Override
    public void setHeader(String name, String value){
        headers.put(name,value);
    }
    @Override
    public void write(String content){
        try {
            buffer=content.getBytes("utf-8");
            flush();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

    }

    @Override
    public void write(byte[] buff) {

    }

    @Override
    public void write(byte[] buff, int start, int len) {

    }

    public void flush() throws IOException {
        StringBuffer sb=new StringBuffer();
        //设置响应行
        sb.append("HTTP/1.1 200 OK\r\n");
        //设置响应头
        sb.append("Access-Control-Allow-Origin: *\r\n");

        sb.append("Content-Type: text/html;charset=utf-8\r\n");
        sb.append("Date: ").append(new Date().toLocaleString()+"\r\n");
        sb.append("Content-Length: ").append(buffer.length+"\r\n");
        if (headers.size()>0){
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                sb.append(entry.getKey()+": ").append(entry.getValue()+"\r\n");
            }
        }

        //响应头和响应体之间隔一行
        sb.append("\r\n");
        //响应体
        sb.append(new String(buffer));
        out.write(sb.toString().getBytes("utf-8"));
        out.flush();
    }
}
